import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";

import { getUserInfo, IGetUserInfoResponse } from "@/api/modules/auth";

export const getUserInfoAction = createAsyncThunk<IGetUserInfoResponse | null>("user/getUseInfo", async () => {
	try {
		return await getUserInfo();
	} catch (error) {
		return null;
	}
});

interface TInitialState {
	userInfo: IGetUserInfoResponse | null;
	token: string | null;
}

const initialState: TInitialState = {
	userInfo: null,
	token: null
};

const userSlice = createSlice({
	name: "user",
	initialState,
	reducers: {
		setToken: (state, { payload }) => {
			state.token = payload;
		}
	},
	extraReducers: builder => {
		builder.addCase(getUserInfoAction.fulfilled, (state, { payload }) => {
			console.log(payload, "payload");
			state.userInfo = {
				isLogin: true
			};
		});
	}
});

export const { setToken } = userSlice.actions;

export default userSlice.reducer;
